package cn.com.jslh.boarpro.main.view.fragment;

import android.Manifest;
import android.content.DialogInterface;
import android.graphics.PointF;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.dlazaro66.qrcodereaderview.QRCodeReaderView;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.com.jslh.boarpro.R;
import cn.com.jslh.boarpro.base.BaseApplication;
import cn.com.jslh.boarpro.base.BaseFragment;
import cn.com.jslh.boarpro.main.contract.AddDuanNaiContract;
import cn.com.jslh.boarpro.main.presenter.AddDuanNaiPresenterImpl;
import cn.com.jslh.boarpro.util.InputDialogUtil;
import cn.com.jslh.boarpro.util.ScanDialog;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;

/**
 * 断奶记录新增
 * 作者：周洲 on 2017/7/26 10:42
 * <p>
 * 邮箱：double0zhou@126.com
 */

public class AddDuanNaiRecordFragment extends BaseFragment implements AddDuanNaiContract.View {
    @BindView(R.id.muzhuTextView)
    TextView muzhuTextView;
    @BindView(R.id.qxZhuShe)
    TextView qxZhuShe;
    @BindView(R.id.dqZhuQun)
    TextView dqZhuQun;
    @BindView(R.id.qxZhuQun)
    TextView qxZhuQun;
    @BindView(R.id.subbtn)
    Button subbtn;
    @BindView(R.id.isTaotai)
    CheckBox isTaotai;
//    private AddDuanNaiPresenterImpl addDuanNaiPresenter;

    private String pinzhong;
    private String dangqianzhushe;

    private AddDuanNaiContract.Presenter presenter;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new AddDuanNaiPresenterImpl(this, getContext());
        presenter.start();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        new RxPermissions(getActivity())
                .request(Manifest.permission.CAMERA)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@NonNull Boolean aBoolean) throws Exception {
                        if (!aBoolean) {
                            Toast.makeText(getContext(), "未获取摄像头权限无法使用扫描二维码功能", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
        View view = inflater.inflate(R.layout.add_duannai_record_layout, container, false);
        unbinder = ButterKnife.bind(this, view);
        //保存状态，避免跳转到扫描界面回来后丢失数据
        InfoShowFragment.initInfoShowFragment(getFragmentManager());
        return view;
    }


    @OnClick({R.id.muzhuTextView, R.id.muzhuInput, R.id.qxZhuShe, R.id.subbtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.muzhuTextView:
                //弹出扫描框，扫描结果放入母猪textView
                new ScanDialog.Builder(getContext())
                        .setQrCodeReadListener(new QRCodeReaderView.OnQRCodeReadListener() {
                            @Override
                            public void onQRCodeRead(final String text, PointF[] points) { //耳号
                                Toast.makeText(getContext(), text, Toast.LENGTH_SHORT).show();
                                InfoShowFragment.getPigInfo(new InfoShowFragment.getInfoSuccessListener() {
                                    @Override
                                    public void success(String s1, String id) {
                                        try {
                                            JSONObject jsonObject = new JSONObject(s1);
                                            String nowZPigFlkID = jsonObject.getString("nowZPigFlkID"); //当前猪舍ID
                                            String nowZPigFlk = jsonObject.getString("nowZPigFlk");//当前猪舍编号
                                            dqZhuQun.setText(nowZPigFlk);
                                            dqZhuQun.setTag(nowZPigFlkID);
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                        muzhuTextView.setText(text);
                                        muzhuTextView.setTag(id);
                                    }
                                }, InfoShowFragment.DuanNaiType, text, SPUtils.getInstance().getString(BaseApplication.FLINEID));
                            }
                        }).create().show();
                break;
            case R.id.muzhuInput:
                InputDialogUtil.showInputDialog(getContext(), "请输入耳号", muzhuTextView.getText().toString(), new InputDialogUtil.DialogListener() {
                    @Override
                    public void getText(final String s) {
                        if (s.equals(""))
                            return;
                        InfoShowFragment.getPigInfo(new InfoShowFragment.getInfoSuccessListener() {
                            @Override
                            public void success(String s1, String id) {
                                try {
                                    JSONObject jsonObject = new JSONObject(s1);
                                    String nowZPigFlkID = jsonObject.getString("nowZPigFlkID"); //当前猪舍ID
                                    String nowZPigFlk = jsonObject.getString("nowZPigFlk");//当前猪舍编号
                                    JSONArray jsonArray = jsonObject.getJSONArray("array");
                                    JSONObject info = jsonArray.getJSONObject(0);
                                    String pzStr = info.getString("FGEN");
                                    String zsStr = info.getString("FZHUSHE");
                                    pinzhong = pzStr.split("：")[1];
                                    dangqianzhushe = zsStr.split("：")[1];
                                    dqZhuQun.setText(nowZPigFlk);
                                    dqZhuQun.setTag(nowZPigFlkID);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                muzhuTextView.setText(s);
                                muzhuTextView.setTag(id);
                            }
                        }, InfoShowFragment.DuanNaiType, s, SPUtils.getInstance().getString(BaseApplication.FLINEID));
                    }
                });
                break;
            case R.id.qxZhuShe:
//                "去向猪舍"
                final List<JSONObject> zhuShes = presenter.getZhuShes();
                if (zhuShes == null || zhuShes.size() == 0) {
                    Toast.makeText(getContext(), "去向猪舍获取失败", Toast.LENGTH_SHORT).show();
                    return;
                }
                final String[] zhusheNames = new String[zhuShes.size()];
                try {
                    for (int i = 0; i < zhuShes.size(); i++) {
                        zhusheNames[i] = zhuShes.get(i).getString("FNAME");
                    }
                    new AlertDialog.Builder(getContext())
                            .setTitle("请选择猪舍")
                            .setItems(zhusheNames, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //获取猪舍信息
                                    try {
                                        qxZhuShe.setText(zhusheNames[which]);
                                        qxZhuShe.setTag(zhuShes.get(which).getString("FID"));
                                        qxZhuQun.setText(zhuShes.get(which).getString("FGOZPIGFLK"));
                                        qxZhuQun.setTag(zhuShes.get(which).getString("FGOZPIGFLKID"));
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.subbtn:
                if (muzhuTextView.getTag() == null) {
                    Toast.makeText(getContext(), "请录入母猪信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (qxZhuShe.getTag() == null) {
                    Toast.makeText(getContext(), "请录入去向猪舍信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                //判断当前母猪是否已经有记录
                if (presenter.isHave(muzhuTextView.getText().toString())) {
                    Toast.makeText(getContext(), "当前记录已经存在，不可重复提交", Toast.LENGTH_SHORT).show();
                    muzhuTextView.setText("请点击扫描录入");
                    muzhuTextView.setTag(null);
                    dqZhuQun.setText("当前种猪群");
                    dqZhuQun.setTag(null);
                    return;
                }
                int isWillOut = 0;
                if(isTaotai.isChecked()){
                    isWillOut= 1;
                }
                subbtn.setEnabled(false);
                presenter.saveDatas(muzhuTextView.getTag().toString(),
                        muzhuTextView.getText().toString(),
                        pinzhong,
                        dangqianzhushe,
                        dqZhuQun.getTag().toString(),
                        dqZhuQun.getText().toString(),
                        qxZhuShe.getTag().toString(),
                        qxZhuShe.getText().toString(),
                        qxZhuQun.getTag().toString(),
                        qxZhuQun.getText().toString(),
                        isWillOut+""
                );
                clear();
                subbtn.setEnabled(true);
                DuanNaiRecordFragment.FlashUI();
                break;
        }
    }

    private void clear() {
        Toast.makeText(getContext(), "保存成功", Toast.LENGTH_SHORT).show();
        InfoShowFragment.getPigInfo(null, InfoShowFragment.Clear);
        muzhuTextView.setText("请点击扫描录入");
        muzhuTextView.setTag(null);
        dqZhuQun.setText("当前种猪群");
        dqZhuQun.setTag(null);
        isTaotai.setChecked(false);
    }

    @Override
    public void setPresenter(AddDuanNaiContract.Presenter presenter) {
        this.presenter = presenter;
    }

}
